//
// = FILENAME
//    configbaud.cc
//
// = AUTHOR(S)
//    Patric Jensfelt
//    
// = COPYRIGHT
//    Copyright (c) 2010 Patric Jensfelt
//
/*----------------------------------------------------------------------*/

#include "Serializer.hh"
#include <iostream>
#include <cstdio>

int main(int argc, char **argv)
{
  const char *optstring = "hd:";
  const char *args = "[-h help] [-d device]";
  const char *device = "/dev/ttyS2";
  char o = getopt(argc, argv, optstring);

  while (o != -1) {
    switch (o) {
    case 'd':
      device = optarg;
      break;
    case 'h':
    case '?':
      fprintf(stderr, "Usage: %s %s\n", argv[0], args);
      return -1;
    }
    o = getopt(argc, argv, optstring);
  }

  Serializer s;

  std::vector<int> baudrates;
  baudrates.push_back(115200);
  baudrates.push_back(19200);
  baudrates.push_back(57600);
  baudrates.push_back(9600);
  baudrates.push_back(4800);
  baudrates.push_back(2400);

  for (unsigned int i = 0; i < baudrates.size(); i++) {
    
    if (s.connect(device, baudrates[i])) {

      if (baudrates[i] == 115200) {
        std::cout << "Serializer board already config for 115200\n";
        s.disconnect();
        return 0;
      } else {
        
        if (!s.setBaudrate(115200)) {
          std::cerr << "Connected at " << baudrates[i] << " but "
                    << " failed to set baudrate to 115200\n";
          return -1;
        } else {
          std::cout << "Set baudrate to 115200\n";
          return 0;
        }

      }

    }

  }

  std::cerr << "Could not connect to the serializer board at any baudrate\n";
  return -1;
}
